#include <boost/bind.hpp>
#include <stdio.h>
#include "serialtest01.h"
#include "ui_serialtest01.h"

SerialTest01::SerialTest01(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SerialTest01),
    m_pCOM1(NULL),
    m_pCOM2(NULL)

{
  ui->setupUi(this);
}

SerialTest01::~SerialTest01()
{
  delete ui;
  if (m_pCOM1!=NULL)
    delete m_pCOM1;
  if (m_pCOM2!=NULL)
    delete m_pCOM2;
}

int SerialTest01::connectSerial()
{
  m_pCOM1=SerialProtocol::createInstance("/dev/ttyS1", 9600, boost::bind(&SerialTest01::handleMessage, this), boost::bind(&SerialTest01::handleConnectionState, this));
  if (m_pCOM1)
    return m_pCOM1->connect(false);
  return -1;
}

void SerialTest01::changeEvent(QEvent *e)
{
  QMainWindow::changeEvent(e);
  switch (e->type())
  {
  case QEvent::LanguageChange:
    ui->retranslateUi(this);
    break;
  default:
    break;
  }
}

void SerialTest01::handleMessage()
{
  /*
  unsigned char t;
  QCheckBox *checks[9];
  checks[1]=ui->cb_Switch_1;
  checks[2]=ui->cb_Switch_2;
  checks[3]=ui->cb_Switch_3;
  checks[4]=ui->cb_Switch_4;
  checks[5]=ui->cb_Switch_5;
  checks[6]=ui->cb_Switch_6;
  checks[7]=ui->cb_Switch_7;
  checks[8]=ui->cb_Switch_8;
  while(m_pCOM1->getBytesAvailable()>1)
  {
    m_pCOM1->getByte(&t);
    fprintf(stderr,"maj: %03i = %02X\n", t>>2,t>>2);
    fprintf(stderr,"cmd: %03i = %02X\n", t&0x03,t&0x03);
    m_pCOM1->getByte(&t);
    fprintf(stderr, "%i -> %i\n", t>>3, t&0x01);
    if ((t>>3) > 0 && (t>>3) < 9)
      (checks[t>>3])->setChecked( (t&0x01) > 0);
  }
  */
}

void SerialTest01::handleConnectionState()
{
  ui->cb_Connected->setChecked(m_pCOM1!=NULL && m_pCOM1->isConnected());
}

void SerialTest01::switchLED(char id, char value)
{
  unsigned char send[2];
  if (m_pCOM1!=NULL)
  {
    send[0]=0xFE;
    send[1]=(id+8) << 3 | 0x02 | value;
    m_pCOM1->sendByte(send[0]);
    m_pCOM1->sendByte(send[1]);
    fprintf(stderr, "sending: %02X %02X\n", send[0], send[1]);
  }
}

void SerialTest01::on_pb_Connect_clicked()
{
  if (m_pCOM1==NULL)
    connectSerial();
}

void SerialTest01::on_pb_LED1_toggled(bool checked)
{
  switchLED(1,checked?1:0);
}

void SerialTest01::on_pb_LED2_toggled(bool checked)
{
  switchLED(2,checked?1:0);
}

void SerialTest01::on_pb_LED3_toggled(bool checked)
{
  switchLED(3,checked?1:0);
}

void SerialTest01::on_pb_LED4_toggled(bool checked)
{
  switchLED(4,checked?1:0);
}

void SerialTest01::on_pb_LED5_toggled(bool checked)
{
  switchLED(5,checked?1:0);
}

void SerialTest01::on_pb_LED6_toggled(bool checked)
{
  switchLED(6,checked?1:0);
}

void SerialTest01::on_pb_LED7_toggled(bool checked)
{
  switchLED(7,checked?1:0);
}

void SerialTest01::on_pb_LED8_toggled(bool checked)
{
  switchLED(8,checked?1:0);
}

void SerialTest01::on_btn_Reset_clicked()
{
  if (m_pCOM1!=NULL)
  {
    m_pCOM1->sendByte(0);
    m_pCOM1->sendByte(0);
  }
}
